package com.framewiki.gpt.service.impl;

import com.cdkjframework.constant.EncodingConsts;
import com.cdkjframework.constant.IntegerConsts;
import com.cdkjframework.entity.http.HttpRequestEntity;
import com.cdkjframework.enums.HttpMethodEnums;
import com.cdkjframework.util.log.LogUtils;
import com.cdkjframework.util.network.http.HttpRequestUtils;
import com.cdkjframework.util.tool.StringUtils;
import com.framewiki.gpt.config.ChatConfig;
import com.framewiki.gpt.config.ChatConfiguration;
import com.framewiki.gpt.dto.request.ChatCompletionRequestDto;
import com.framewiki.gpt.dto.request.CreateChatCompletionDto;
import com.framewiki.gpt.dto.response.ChatCompletionResponseDto;
import com.framewiki.gpt.dto.response.ChatMessagesDto;
import com.framewiki.gpt.service.ChatService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ProjectName: framewiki-gpt
 * @Package: com.framewiki.gpt.service.impl
 * @ClassName: ChatServiceImpl
 * @Description: java类作用描述
 * @Author: xiaLin
 * @Date: 2023/6/16 22:58
 * @Version: 1.0
 */
@Service
@RequiredArgsConstructor
public class ChatServiceImpl implements ChatService {

  /**
   * 日志
   */
  private LogUtils logUtils = LogUtils.getLogger(ChatServiceImpl.class);

  /**
   * 配置信息
   */
  private final ChatConfiguration configuration;

  /**
   * 地址
   */
  private final ChatConfig chatConfig;

  /**
   * 创建对话
   *
   * @param content 消息内容
   */
  @Override
  public ChatCompletionResponseDto createChatCompletion(CreateChatCompletionDto content) {
    if (StringUtils.isNullAndSpaceOrEmpty(content.getModel())) {
      content.setModel(model);
    }
    List<ChatMessagesDto> messages = new ArrayList<>();
    ChatMessagesDto systemMessage = new ChatMessagesDto(role, content.getContent());
    messages.add(systemMessage);
    ChatCompletionRequestDto chatCompletionRequest = ChatCompletionRequestDto.builder()
        .model(content.getModel())
        .messages(messages)
        .user(content.getUser())
        .maxTokens(IntegerConsts.ONE_HUNDRED * IntegerConsts.FIVE)
        .temperature(BigDecimal.ONE)
        .build();

    HttpRequestEntity request = new HttpRequestEntity();
    request.setRequestAddress(chatConfig.getCreateChatCompletion());
    request.setMethod(HttpMethodEnums.POST);
    request.setData(chatCompletionRequest);
    request.setCharset(EncodingConsts.UTF8);
    // 请求头
    Map<String, String> headerMap = new HashMap<>(IntegerConsts.ONE);
    headerMap.put(AUTHORIZATION, BEARER + configuration.getOpenaiApiKey());
    request.setHeaderMap(headerMap);
    ChatCompletionResponseDto response = null;
    try {
      response = HttpRequestUtils.httpRequest(request, ChatCompletionResponseDto.class);
      response.setUser(content.getUser());
    } catch (Exception e) {
      logUtils.error(e);
    }
    // 返回结果
    return response;
  }
}
